﻿using SingleBlog.Core.Services;
using System;
using System.Threading.Tasks;

namespace SingleBlog.Framework
{
    /// <summary>
    /// 表示使用 SMTP 的方式发送消息。
    /// </summary>
    public class SmtpMessageSender : IMessageSender
    {
        private readonly SettingService _settingService;
        /// <summary>
        /// 初始化 <see cref="SmtpMessageSender"/> 类的新实例。
        /// </summary>
        /// <param name="settingService">注入的 <see cref="SettingService"/> 对象。</param>
        public SmtpMessageSender(SettingService settingService)
        {
            _settingService = settingService;
        }
        /// <summary>
        /// 使用系统配置的 SMTP 设置发送邮件。
        /// </summary>
        /// <param name="message">邮件的消息。</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">message is null.</exception>
        /// <exception cref="InvalidCastException">message 不是 MailMessage 类的派生对象。</exception>
        public Task SendAsync(IMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var mailMessage = message as MailMessage;
            if (mailMessage == null)
            {
                throw new InvalidCastException("当前 message 对象必须是 MailMessage 对象派生对象或本身。");
            }

            var smtpSetting = _settingService.GetSmtpSetting();


            var mailMsg = new System.Net.Mail.MailMessage(smtpSetting.GetSender(), new System.Net.Mail.MailAddress(mailMessage.To))
            {
                Subject = mailMessage.Subject,
                Body = mailMessage.Body,
                IsBodyHtml = true
            };

            return smtpSetting.GetClient().SendMailAsync(mailMsg);
        }
    }
}
